
const requestify = require('requestify');
const request = require('request')
import * as msgdefine from "./msgdefine";
import {
    Contact,
    Contact_Data,
    Message,
    Message_Data,
    getDisplayName,
    convertEmoji
} from './interface'

const Wechat = require('wechat4u');
import botMgr from "./botMgr"
function sleep(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
interface roomConfig {
    uuid: string;
    winner_yell: string;
    yell_context: string;
    yell_delay: number;
    gameType: string;
    playerMaxCount: number;
    maxRound: number;
    config: any;
}
interface runingRoom {
    createTime: number;//创建时间，超过1.5小时后自动删除房间
    last_yell: number;//最后呼叫时间
    roomId: number;//

    currentPlayerCount: number;
    isyelledfull: boolean;
    last_update: number;
    result: {
        nickName: string;
        point: number;
        ip: string;
        gps: number[];
    }[] | null;
    bindConfigData: roomConfig;//拷贝过来的配置


}
//运行时的group结构
interface group {
    group_name: string;
    group_userName: string;
    group_id: string;//我们服务器上的id
    agent: string;
    qrcode_url: string;
    pause: boolean;
    runtime: {
        last_notice: number;//最后公告时间
        last_talk: number;//最后玩家说话时间
        qrcode: {
            mediaId: string | null;
            uploadTime: number;
            url: string;
        };
        last_createRoom: {};//uuid:time
        rooms: runingRoom[];
        members: string[];
    };
    config: {//所有配置
        start_hour: number;
        end_hour: number;
        notice: string;//空字符串表示关闭下同
        notice_delay: number;
        new_member_yell: string;
        qrcode_url: string;
        keyword: string[];//是关键字,内容,关键字,内容

        room: roomConfig[];
    } | null;
}
enum ItemType {
    text,
    pic,
    video
}
interface talkItem {
    itemType: ItemType;
    toUserName: string;
    context: any;
}
export default class userbot {
    private _user: string = ""
    private _wechat: any = null; //wechat实例
    private _isLogin: boolean = false;//是否已经login
    private _botMgr: botMgr = null;
    private _isOver: boolean = false;//logout
    private _isPause: boolean = false;//用户手动暂停状态
    private _configedGroup: Map<string, group> = new Map();//当前配置了的群
    // private _talkTime: any = null;
    private _talkQuee: talkItem[] = []; //聊天队列
    constructor(mgr: botMgr, user: string, snykey: any) {
        this._botMgr = mgr;
        this._user = user;
        this._wechat = new Wechat(snykey);
        let self = this;
        // this._talkTime = setInterval(() => {
        //     this.runTalk();
        // }, 500);
        this.thread();
        if (this._wechat.PROP.uin) {
            // 存在登录数据时，可以随时调用restart进行重启
            this._wechat.restart()
        } else {
            this._wechat.start()
        }

        this._wechat.on('login', () => {
            console.log('logined' + this._user)
            this._botMgr.loginOk(this._user, this);
            // 保存数据，将数据序列化之后保存到任意位置
            this._botMgr.cs_login({
                user: this._user,
                snykey: this._wechat.botData
            })
            self._isLogin = true;

        });
        this._wechat.on('logout', () => {
            console.log('logout:' + this._user)
            if (self._isLogin) {
                this._botMgr.cs_loginout({
                    user: this._user
                })
            }
            self._isLogin = false;
            self._isOver = true;
            //   clearInterval(this._talkTime);
            self._talkQuee = [];
        });

        this._wechat.on('contacts-updated', (contacts: Contact[]) => {
            self.onReciveContacts(contacts);

        });
        this._wechat.on('message', (msg: Message) => {
            console.log(this._user + " get message")
            self.onReciveMessage(msg);
        })
        this._wechat.on('error', (err: any) => {
            console.log(this._user + "error" + err);
        });

        this._wechat.on("uuid", uuid => {
            this._botMgr.cs_new({
                user: this._user,
                uuid: uuid
            })
        });
        // this._wechat.setRollingMessageGetter(function () {
        //     //
        //     return '小助理运行中:' + new Date().toLocaleString()
        // });
    }
    public sendText(toUserName: string, msg: string) {
        this._talkQuee.push({
            itemType: ItemType.text,
            context: msg,
            toUserName: toUserName
        });
        // this._wechat.sendText(msg, toUserName).then(() => { });
    }
    public sendPic(toUserName: string, mediaId: string) {
        this._talkQuee.push({
            itemType: ItemType.pic,
            context: mediaId,
            toUserName: toUserName
        });
        // this._wechat.sendPic(mediaId, toUserName).then(() => { });
    }
    public sendVideo(toUserName: string, mediaId: string) {
        this._talkQuee.push({
            itemType: ItemType.video,
            context: mediaId,
            toUserName: toUserName
        });
        // this._wechat.sendPic(mediaId, toUserName).then(() => { });
    }
    private runTalk() {
        if (this._talkQuee.length <= 0 || this._isLogin == false) return;
        let item: talkItem = this._talkQuee.shift();
        switch (item.itemType) {
            case ItemType.text: {
                this._wechat.sendText(item.context, item.toUserName).then(() => { });
            } break;
            case ItemType.pic: {
                this._wechat.sendPic(item.context, item.toUserName).then(() => { });
            } break;
            case ItemType.video: {
                this._wechat.sendVideo(item.context, item.toUserName).then(() => { });
            } break;
        }

    }
    public async sendQrCode(gr: group) {
        let qrurl = gr.qrcode_url || gr.config.qrcode_url;

        if (gr.config && qrurl && qrurl != "") {
            if (gr.runtime.qrcode.mediaId == null || gr.runtime.qrcode.mediaId == "" || Date.now() - gr.runtime.qrcode.uploadTime > 1000 * 1000 || gr.runtime.qrcode.url != qrurl) {
                let mediaId = await this.updateMedia(gr.group_userName, qrurl);
                if (mediaId != null && mediaId != "") {
                    gr.runtime.qrcode.mediaId = mediaId;
                    gr.runtime.qrcode.uploadTime = Date.now();
                    gr.runtime.qrcode.url = qrurl;
                }
            }
            if (gr.runtime.qrcode.mediaId != null && gr.runtime.qrcode.mediaId != "" || Date.now() - gr.runtime.qrcode.uploadTime < 1000 * 1000) {
                this.sendPic(gr.group_userName, gr.runtime.qrcode.mediaId);
            }
        }

    }

    public async updateMedia(toUserName: string, url: string): Promise<string | null> {
        try {
            let res = await this._wechat.uploadMedia(request(url), toUserName.replace(/\@/g, "") + require("path").extname(url), toUserName);
            return res.mediaId;
        } catch (err) {
            return null;
        }
    }
    private isGroupChangeName(contact: Contact) {

        for (let key of this._configedGroup.keys()) {
            let gr = this._configedGroup.get(key);
            if (gr.group_userName == contact.UserName) {
                if (getDisplayName(contact) != gr.group_name) {
                    //向服务器发包
                    if (gr.group_id && gr.group_id != "") {
                        this._botMgr.cs_groupnamechange({
                            user: this._user,
                            group_id: gr.group_id,
                            group_name: getDisplayName(contact)
                        })
                    }
                    gr.group_name = getDisplayName(contact);
                    this._configedGroup.set(gr.group_name, gr);
                    this._configedGroup.delete(key);

                }
                return;
            }
        }
    }
    private async onReciveContacts(contacts: Contact[]) {
        //貌似群里面的人更新也会走
        for (let contactdata of contacts) {

            if (contactdata.isSelf) continue;
            if (this._wechat.Contact.isRoomContact(contactdata)) {
                //群
                this.isGroupChangeName(contactdata)
                if (!this._configedGroup.has(getDisplayName(contactdata))) {
                    //没有这个群
                    this._botMgr.cs_getgroupconfig({
                        user: this._user,
                        group_name: getDisplayName(contactdata)
                    });

                }
                // let contacts = await this._wechat.batchGetContact([{ UserName: contactdata.UserName }]);
                // this._wechat.updateContacts(contacts);
            }
        }
    }
    private onReciveMessage(msg: Message) {
        if (msg.isSendBySelf) return;

        let contact = this._wechat.contacts[msg.FromUserName];

        //这部分处理我被拉群，我被t，，，现在就剩下群里别人邀请

        if (/^@@|@chatroom$/.test(msg.ToUserName) || /^@@|@chatroom$/.test(msg.FromUserName)) {
            this.onReciveGroupMessage(msg);
        } else {
            //this.help(msg)
        }


    }


    private help(msg: Message) {

        //帮助类
        let text = msg.Content.replace(/ /g, "");
        let commandlist = ["帮助", "解散", "暂停", "继续"];
        let cmd = -1;
        for (var i = 0; i < commandlist.length; i++) {
            if (text.indexOf(commandlist[i]) == 0) {
                cmd = i;
                break;
            }
        }
        switch (cmd) {
            //				<br>==========<br>重置:重新读取您的群配置<br>例子:重置\
            case 0: {
                this.sendText(msg.FromUserName, "您可以对小秘说出命令来操作,目前支持的命令有:解散、暂停、继续\
					\n==========\n解散:解散代开房的房间\n例子:解散598797\
					\n==========\n暂停:暂停小秘所有功能，可通过继续指令恢复使用\n例子:暂停\
					\n==========\n继续:恢复暂停指令停止小秘所有功能\n例子:继续");
            } break;

            case 1: {
                var param = parseInt(msg.Content.slice(commandlist[cmd].length));
                this.sendText(msg.FromUserName, "请到小助理管理后台停用该房间");
                //this._
                // this._callbacks.deleteRoom.call(this._callbacks.self, [param]);
            } break;
            case 2: {
                this._isPause = true;
                this.sendText(msg.FromUserName, "小秘功能已经全部暂停，您可以通过 继续 指令恢复使用");
            } break;
            case 3: {
                this._isPause = false;
                this.sendText(msg.FromUserName, "小秘功能恢复运行");
            } break;

            default: {
                this.sendText(msg.FromUserName, "你好！我是小蜜,可以对我说 帮助 ,我会告诉你怎么和我沟通！当前小秘处于" + (this._isPause ? "暂停状态" : "运行状态"));
            };
        }
    }
    private async convertMsg(msg: Message): Promise<{ toUser: Contact, fromUser: Contact, isRoomAt: boolean, Content: string }> {
        let Content = msg.OriginalContent;
        let isRoomAt: boolean = false;
        let toUser = this._wechat.contacts[msg.ToUserName];
        let fromUser = (msg.isSendBySelf ? this._wechat.user : this._wechat.contacts[msg.FromUserName]);
        Content = Content.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/<br\/>/g, '\n');
        if (/^@@|@chatroom$/.test(msg.isSendBySelf ? msg.ToUserName : msg.FromUserName)) {
            isRoomAt = (Content.indexOf("@") == 0 && Content.indexOf("\u2005") != -1);
        }

        if (msg.isSendBySelf) {
            if (/^@@|@chatroom$/.test(msg.ToUserName)) {
                //我发送的群消息，这时候全部都是昵称，from是我自己，to是群，所以如果是@就要修改touser为真是的人
                //我发的内容就直接ok了
                if (isRoomAt) {
                    let pos = Content.indexOf("\u2005");
                    let userNickName = Content.substring(1, pos);
                    Content = Content.substr(pos).replace("\u2005", "");
                    toUser = this._wechat.contacts[msg.ToUserName].MemberList.find((member: Contact_Data) => {
                        return member.UserName === userNickName || member.NickName === userNickName || member.RemarkName === userNickName || member.DisplayName === userNickName;
                    });
                    if (toUser == null) {
                        toUser = this._wechat.contacts[msg.ToUserName];
                        isRoomAt = false;
                    }
                }
            }
        } else {
            if (/^@@|@chatroom$/.test(msg.FromUserName)) {
                //群消息，别人发的，这时候from是群，to是我自己，修改from为真实的人
                if (msg.MsgType != this._wechat.CONF.MSGTYPE_SYS) {
                    let pos = Content.indexOf(":\n");
                    let fromUserName = Content.substring(0, pos);

                    Content = Content.substr(pos).replace(":\n", "");
                    fromUser = this._wechat.contacts[msg.FromUserName].MemberList.find((member: Contact_Data) => {
                        return member.UserName === fromUserName;
                    })
                    if (getDisplayName(fromUser) == "") {

                        try {
                            //let contacts = await this._wechat.batchGetContact([{ UserName: fromUserName, EncryChatRoomId: this._wechat.contacts[msg.FromUserName].EncryChatRoomId }]);
                            let contacts = await this._wechat.batchGetContact([{ UserName: msg.FromUserName }]);
                            this._wechat.updateContacts(contacts);

                        } catch (err) {

                        }
                    }
                    //如果是@修改to为真实的人，否则to应该是群
                    if (isRoomAt) {
                        let pos = Content.indexOf("\u2005");
                        let userNickName = Content.substring(1, pos);
                        Content = Content.substr(pos).replace("\u2005", "");
                        toUser = this._wechat.contacts[msg.FromUserName].MemberList.find((member: Contact_Data) => {
                            return member.UserName === userNickName || member.NickName === userNickName || member.RemarkName === userNickName || member.DisplayName === userNickName;
                        })
                        if (toUser == null) {
                            toUser = this._wechat.contacts[msg.FromUserName];
                            isRoomAt = false;
                        }
                    } else {
                        toUser = this._wechat.contacts[msg.FromUserName];
                    }
                }
                //还要修改内容

            }
        }
        return {
            toUser: toUser,
            fromUser: fromUser,
            isRoomAt: isRoomAt,
            Content: Content
        }
    }
    private async onReciveGroupMessage(msg: Message) {

        let theMsg: {
            toUser: Contact, fromUser: Contact, isRoomAt: boolean, Content: string
        } = await this.convertMsg(msg);
        let contact: Contact = this._wechat.contacts[msg.FromUserName];
        let gr: group = this._configedGroup.get(getDisplayName(contact));
        if (msg.MsgType == this._wechat.CONF.MSGTYPE_TEXT) {
            if (theMsg.isRoomAt && theMsg.Content === "启用配置" && theMsg.toUser.UserName == this._wechat.user.UserName) {
                this._botMgr.cs_configgroup({
                    user: this._user,
                    group_name: getDisplayName(contact),
                    group_id: gr ? gr.group_id : null
                })
                return;
            }
        }

        if (gr && gr.group_id && gr.config) {
            //已经配置了的房间->记录lasttalk->发送邀请->智能聊天
            if (msg.MsgType == this._wechat.CONF.MSGTYPE_SYS) {
                if (theMsg.Content.indexOf("加入了群聊") != -1) {
                    this._botMgr.cs_invitegroup({
                        user: this._user,
                        group_id: gr.group_id,
                        tip: theMsg.Content
                    });
                    //发送欢迎辞
                    if (gr.config.new_member_yell && gr.config.new_member_yell != "") {
                        let p = theMsg.Content.indexOf("邀请");
                        let str = theMsg.Content.substr(p);
                        str = str.replace(/\"/g, "").replace("邀请", "").replace("加入了群聊", "");
                        this.sendText(msg.FromUserName, "@" + convertEmoji(str) + "\u2005" + gr.config.new_member_yell);
                    }
                }
            } else {
                //记录最后聊天

                if (msg.MsgType == this._wechat.CONF.MSGTYPE_TEXT && theMsg.isRoomAt && theMsg.toUser.UserName == this._wechat.user.UserName) {
                    this.smartTalk(gr, contact, theMsg.fromUser, theMsg.Content);
                }


            }
            gr.runtime.last_talk = Date.now();
            this._configedGroup.set(getDisplayName(contact), gr);
        }

    }
    private smartTalk(groupconfig: group, groupcontact: Contact, from: Contact, content: string) {


        let text = content.replace(/\n/g, "").toUpperCase();
        for (let i = 0; i < groupconfig.config.keyword.length; i++) {
            if (text.indexOf(groupconfig.config.keyword[i]) != -1) {
                this.sendText(groupcontact.UserName, "@" + getDisplayName(from) + "\u2005" + groupconfig.config.keyword[i + 1]);
                return;
            }
        }

        var robot = "http://www.tuling123.com/openapi/api";
        requestify.post("http://www.tuling123.com/openapi/api", {
            key: "f3bbe5fe0363417587b29bcdc313b5c6",
            info: text,
            userid: from.UserName,
            txt: text
        }).then((response: any) => {
            let res = response.getBody();
            try {
                res = JSON.parse(res);
                if (res.code == 100000) {
                    this.sendText(groupcontact.UserName, "@" + getDisplayName(from) + "\u2005" + res.text);
                }
            } catch (e) {

            }

        })

    }
    private isInWorkTime(gr: group): boolean {

        let date = new Date();
        if (gr.config.start_hour < gr.config.end_hour) {
            if (date.getHours() >= gr.config.start_hour && date.getHours() < gr.config.end_hour) {
                return true;
            }
        } else {
            if ((date.getHours() >= gr.config.start_hour && date.getHours() < 24) || (date.getHours() >= 0 && date.getHours() < gr.config.end_hour)) {
                return true;
            }
        }
        return false;
    }
    private createAgentRoom(gr: group) {
        //开房在收报有个立刻创建，创建原则，这种配置有房间并且没满
        if (gr && gr.config && gr.config.room && gr.config.room.length > 0 && gr.agent && gr.agent != "") {
            gr.config.room.forEach(room => {
                if (gr.runtime.last_createRoom[room.uuid] != null && Date.now() - gr.runtime.last_createRoom[room.uuid] < 10000) return;
                let noneedCreate = gr.runtime.rooms.findIndex(r => {
                    return (r.bindConfigData.uuid == room.uuid && r.currentPlayerCount != r.bindConfigData.playerMaxCount)
                })
                if (noneedCreate == -1) {
                    gr.runtime.last_createRoom[room.uuid] = Date.now();
                    this._botMgr.cs_creategame({
                        agent: gr.agent,
                        group_id: gr.group_id,
                        user: this._user,
                        gameType: room.gameType,
                        playerMaxCount: room.playerMaxCount,
                        maxRound: room.maxRound,
                        config: room.config,
                        roomUUID: room.uuid
                    });
                }
            })
        }

    }
    private async thread() {
        let lastRun = 0;
        while (this._isOver == false) {
            //先聊天
            if (this._isPause == false && this._isLogin) {
                //执行group命令
                let date = new Date();
                if (date.getTime() - lastRun >= 3000) {
                    lastRun = Date.now();
                    for (let gr of this._configedGroup.values()) {
                        if (gr && gr.group_id && gr.config && this.isInWorkTime(gr) && this._wechat.contacts[gr.group_userName] && gr.pause == false) {
                            //公告
                            if (gr.config.notice && gr.config.notice != "" && Date.now() - gr.runtime.last_notice > gr.config.notice_delay * 60000) {
                                gr.runtime.last_notice = Date.now();
                                this.sendText(gr.group_userName, gr.config.notice);
                            }

                            //主动刷新房间,超时房间自动删除
                            //  let deleteRooms = [];
                            gr.runtime.rooms.forEach(rr => {
                                // if (Date.now() - rr.createTime > 150 * 60 * 1000) {
                                //     deleteRooms.push(rr.roomId);
                                //     return;
                                // }
                                if (Date.now() - rr.last_update > 5000) {
                                    this._botMgr.requestRoomRefash({
                                        group_id: gr.group_id,
                                        user: this._user,
                                        gameType: rr.bindConfigData.gameType,
                                        roomId: rr.roomId
                                    });
                                }
                            })
                            // gr.runtime.rooms = gr.runtime.rooms.filter(r => {
                            //     return deleteRooms.indexOf(r.roomId) == -1
                            // })
                            this.yellRooms(gr);
                            //创建房间
                            this.createAgentRoom(gr);
                            //推群检测
                            let newUsers: string[] = [];
                            try {
                                this._wechat.contacts[gr.group_userName].MemberList.forEach(mem => {
                                    let name = getDisplayName(mem);
                                    if (name != "") {
                                        newUsers.push(name);
                                    }
                                });
                                let outusers = gr.runtime.members.filter(u => {
                                    if (newUsers.indexOf(u) == -1) return true;
                                    return false;
                                });
                                if (outusers.length > 0) {
                                    this._botMgr.cs_leavegroup({
                                        user: this._user,
                                        group_id: gr.group_id,
                                        member: outusers
                                    })
                                }
                                gr.runtime.members = newUsers;
                            } catch (err) { }

                        }
                    }
                }
                this.runTalk();
            }

            await sleep(3000);
        }
    }
    private async groupBroadCast(gr: group, type: string, context: string) {
        if (gr.group_userName && gr.config) {
            if (type == "text") {
                this.sendText(gr.group_userName, context);
            } else {
                if (context && context != "") {
                    if (type == "image") {
                        this.sendPic(gr.group_userName, context);
                    } else {
                        this.sendVideo(gr.group_userName, context);
                    }
                }
            }

        }
    }
    public async sc_broadcast(data: msgdefine.i_sc_broadcast) {
        let mediaId = null;
        for (let gr of this._configedGroup.values()) {
            let isFind = data.whitelist.findIndex((white) => {
                if (white.whiteType == msgdefine.WhiteType.agent && gr && gr.agent == white.keyword) return true;
                if (white.whiteType == msgdefine.WhiteType.groupname && gr.group_name.indexOf(white.keyword) != -1) return true;
                return false;
            })
            if (isFind != -1) continue;
            if (mediaId == null || mediaId == "") {
                mediaId = await this.updateMedia(gr.group_userName, data.context);
            }
            this.groupBroadCast(gr, data.type, mediaId);
        }

    }
    public sc_grouppause(data: msgdefine.i_sc_grouppause) {
        let gr: group = this.getConfigGroupByGroupId(data.group_id)

        if (gr == null) return;
        gr.pause = data.pause;
        if (gr.pause == true) {
            gr.runtime.last_createRoom = {};
            gr.runtime.last_notice = 0;
            gr.runtime.last_talk = Date.now();
            gr.runtime.rooms = [];
        }
    }
    public sc_groupconfig(data: msgdefine.i_sc_groupconfig) {

        for (let userName in this._wechat.contacts) {
            let contact: Contact = this._wechat.contacts[userName];
            if (this._wechat.Contact.isRoomContact(contact)) {
                if (getDisplayName(contact) == (data.group_name)) {
                    let gr: group = this._configedGroup.get(data.group_name);
                    if (gr) {
                        gr.group_id = data.group_id;
                        gr.config = data.config;
                        gr.group_userName = userName;
                        gr.agent = data.agent;
                        gr.qrcode_url = data.qrcode_url;
                        gr.pause = data.pause;
                    } else {
                        let members: string[] = [];
                        contact.MemberList.forEach(mem => {
                            let name = getDisplayName(mem);
                            if (name != "")
                            { members.push(name); }
                        })
                        gr = {
                            qrcode_url: data.qrcode_url,
                            agent: data.agent,
                            group_id: data.group_id,
                            config: data.config,
                            group_name: data.group_name,
                            group_userName: userName,
                            pause: data.pause,
                            runtime: {
                                members: members,
                                last_createRoom: {},
                                last_notice: 0,
                                last_talk: Date.now(),
                                qrcode: {
                                    mediaId: "",
                                    uploadTime: 0,
                                    url: ""
                                },
                                rooms: []
                            }
                        }
                    }
                    if (gr.config == null || gr.pause == true) {
                        gr.runtime.last_createRoom = {};
                        gr.runtime.last_notice = 0;
                        gr.runtime.last_talk = Date.now();
                        gr.runtime.rooms = [];
                    }
                    this._configedGroup.set(data.group_name, gr);
                    return;
                }
            }
        }
        if (data.group_id && data.group_id != "") {
            for (let gr of this._configedGroup.values()) {
                if (gr.group_id == data.group_id) {
                    let contact: Contact = this._wechat.contacts[gr.group_userName];
                    gr.group_name = getDisplayName(contact);
                    gr.group_id = data.group_id;
                    gr.config = data.config;
                    gr.agent = data.agent;
                    gr.qrcode_url = data.qrcode_url;
                    gr.pause = data.pause;

                    if (gr.config == null || gr.pause == true) {
                        gr.runtime.last_createRoom = {};
                        gr.runtime.last_notice = 0;
                        gr.runtime.last_talk = Date.now();
                        gr.runtime.rooms = [];
                    }
                    this._configedGroup.delete(data.group_name);
                    this._configedGroup.set(getDisplayName(contact), gr);
                    return;
                }
            }
        }
        console.log(this._user + "未找到该群:" + data.group_name);

    }
    public sc_contactgroups(data: msgdefine.i_sc_contactgroups) {
        let contactgroups: {
            group_name: string;
            group_id: string | null;//如果被配置了那么就有这个量
            memberCount: number;
        }[] = [];
        console.log(Object.keys(this._wechat.contacts).length)
        for (let userName in this._wechat.contacts) {
            let contact: Contact = this._wechat.contacts[userName];

            if (this._wechat.Contact.isRoomContact(contact)) {
                let g: group = this._configedGroup.get(getDisplayName(contact))

                contactgroups.push({
                    group_name: getDisplayName(contact),
                    memberCount: contact.MemberCount,
                    group_id: g ? g.group_id : null
                })
            }
        }
        this._botMgr.cs_contactgroups({
            user: this._user,
            contactgroups: contactgroups
        })
    }
    private getConfigGroupByGroupId(id: string): group {
        let gr: group = null;
        for (let g of this._configedGroup.values()) {
            if (g.group_id == id) {
                return g;
            }
        }
        return null;
    }
    public sc_creategame(data: msgdefine.i_sc_creategame) {
        let gr = this.getConfigGroupByGroupId(data.group_id);
        let config: roomConfig = gr.config.room.find((r) => {
            return r.uuid == data.roomUUID;
        })
        if (config) {
            gr.runtime.rooms.push({
                createTime: Date.now(),
                last_yell: Date.now(),
                roomId: data.roomId,
                currentPlayerCount: 0,

                isyelledfull: false,
                result: null,
                bindConfigData: config,
                last_update: Date.now()
            })
            //需要不需要set回去？
            //喊房间咯
            let text = config.yell_context + "\n◢█████████◣\n房号[" + data.roomId + "]" + " 速度！\n◥█████████◤\n" + "点击下面链接直接进入游戏:\nhttp://ddmj.viyo.me/" + data.roomId;
            this.sendText(gr.group_userName, text);
        }
    }
    private yellRoom(gr: group, room: runingRoom): boolean {
        if (room.result && room.result.length > 0) {
            var counterString = "房号: " + room.roomId + ",游戏开始时间:";
            var dat = new Date(room.createTime);
            counterString = counterString + dat.getHours() + ":" + dat.getMinutes() + ",游戏结束于:";
            dat = new Date();
            counterString = counterString + dat.getHours() + ":" + dat.getMinutes() + "\n";
            let winner: { nickName: string, point: number } = { nickName: "", point: -999999999 };
            for (var j = 0; j < room.result.length; j++) {
                counterString = counterString + room.result[j].nickName + "分数 : [ " + room.result[j].point + " ]\n";
                if (room.result[j].point > winner.point) {
                    winner = room.result[j];
                }
            }
            this.sendText(gr.group_userName, counterString);

            if (room.bindConfigData.winner_yell && room.bindConfigData.winner_yell != "" && winner.point > 0) {
                this.sendText(gr.group_userName, "@" + winner.nickName + "\u2005" + room.bindConfigData.winner_yell);
            }

            if ((gr.qrcode_url && gr.qrcode_url != "") || (gr.config.qrcode_url && gr.config.qrcode_url != "")) {
                this.sendQrCode(gr).then(() => { });
            }
            return false;
        } else {
            if (room.bindConfigData.playerMaxCount != room.currentPlayerCount) {
                room.isyelledfull = false;
                if (room.bindConfigData.yell_context && room.bindConfigData.yell_context != "") {
                    if ((Date.now() - room.last_yell > 3600 * 1000) || (gr.runtime.last_talk + 0 * 1000 > room.last_yell && Date.now() - room.last_yell > room.bindConfigData.yell_delay * 1000)) {
                        let context = ["", "一", "二", "三", "四"]
                        let text = room.bindConfigData.yell_context + "\n◢█████████◣\n房号[" + room.roomId + "]" + context[room.bindConfigData.playerMaxCount] + "缺" + context[(room.bindConfigData.playerMaxCount - room.currentPlayerCount)] + "\n◥█████████◤\n" + "点击下面链接直接进入游戏:\nhttp://ddmj.viyo.me/" + room.roomId;
                        room.last_yell = Date.now();
                        this.sendText(gr.group_userName, text);
                    }
                }
                //自动喊房间
            } else {
                if (room.isyelledfull == false) {
                    //喊人满
                    this.sendText(gr.group_userName, "房号:[" + room.roomId + "]已经人满,请各位进入游戏欢畅玩乐吧！祝好运！");
                    room.isyelledfull = true;
                    //如果还存在这种房间立刻开房
                    // if (gr.config && gr.config.room) {
                    //     let roomconfig = gr.config.room.find(r => {
                    //         return r.uuid == room.bindConfigData.uuid;
                    //     })
                    //     if (roomconfig && this.isInWorkTime(gr) && gr.agent && gr.agent != "") {
                    //         //这种房间存在,应该使用新配置去创建
                    //         if (gr.runtime.last_createRoom[roomconfig.uuid] == null || Date.now() - gr.runtime.last_createRoom[roomconfig.uuid] > 10000) {
                    //             let noneedCreate = gr.runtime.rooms.findIndex(r => {
                    //                 return (r.bindConfigData.uuid == roomconfig.uuid && r.currentPlayerCount != r.bindConfigData.playerMaxCount)
                    //             })
                    //             if (noneedCreate == -1) {
                    //                 gr.runtime.last_createRoom[roomconfig.uuid] = Date.now();
                    //                 this._botMgr.cs_creategame({
                    //                     agent: gr.agent,
                    //                     group_id: gr.group_id,
                    //                     user: this._user,
                    //                     gameType: roomconfig.gameType,
                    //                     playerMaxCount: roomconfig.playerMaxCount,
                    //                     maxRound: roomconfig.maxRound,
                    //                     config: roomconfig.config,
                    //                     roomUUID: roomconfig.uuid
                    //                 });
                    //             }

                    //         }
                    //     }
                    // }
                }
            }

        }
        return true;
    }
    private yellRooms(gr: group) {
        let temprooms: runingRoom[] = [];
        for (let i = 0; i < gr.runtime.rooms.length; i++) {

            let room = gr.runtime.rooms[i];
            if (Date.now() - room.last_update > 15 * 60 * 1000 || Date.now() - room.createTime > 175 * 60 * 1000) continue;
            if (this.yellRoom(gr, room)) {
                temprooms.push(room);
            }
        }
        gr.runtime.rooms = temprooms;
    }
    public sc_gameinfo(data: {
        group_id: string;
        user: string;
        roomId: number;
        currentPlayerCount: number | null;
        result: {
            nickName: string;
            point: number;
            ip: string;
            gps: number[];
            uId: string;
        }[] | null;
    }) {
        let gr = this.getConfigGroupByGroupId(data.group_id);
        if (gr) {
            for (let i = 0; i < gr.runtime.rooms.length; i++) {
                if (gr.runtime.rooms[i].roomId == data.roomId) {
                    let isPlayerChange = (gr.runtime.rooms[i].currentPlayerCount != data.currentPlayerCount);
                    gr.runtime.rooms[i].currentPlayerCount = data.currentPlayerCount;
                    gr.runtime.rooms[i].result = data.result;
                    gr.runtime.rooms[i].last_update = Date.now();
                    if (isPlayerChange) {
                        //  gr.runtime.rooms[i].last_yell = 0;
                        if (Date.now() - gr.runtime.rooms[i].last_yell > gr.runtime.rooms[i].bindConfigData.yell_delay * 1000) {
                            gr.runtime.rooms[i].last_yell = Date.now() - 3601 * 1000;

                        }
                    }
                    // if (isPlayerChange || (data.result && data.result.length > 0)) {
                    //     if (this.yellRoom(gr, gr.runtime.rooms[i], isPlayerChange) == false) {
                    //         let temp = gr.runtime.rooms.splice(0, i);
                    //         gr.runtime.rooms = temp.concat(gr.runtime.rooms.slice(1));
                    //     }
                    // }
                    return;
                }
            }
        }
    }
    public sc_configgroup(data: msgdefine.i_sc_configgroup) {
        //返回配置链接
        let gr: group = null;
        if (data.group_id) {
            gr = this.getConfigGroupByGroupId(data.group_id);
        } else {
            gr = this._configedGroup.get(data.group_name);
        }
        if (gr) {
            this.sendText(gr.group_userName, "点击链接开始配置:\n" + data.url);
        }

    }
    public sc_deleteroom(data: msgdefine.i_sc_deleteroom) {
        let gr: group = null;
        if (data.group_id) {
            gr = this.getConfigGroupByGroupId(data.group_id);
            if (gr) {
                gr.runtime.rooms = gr.runtime.rooms.filter(r => {
                    return !(r.roomId == data.roomId)
                })
            }
        }

    }
    public sc_loginout(data: msgdefine.i_sc_loginout) {
        this._wechat.logout();

    }
}